package lxs.tool.liberator.work.service.imp;

import lxs.tool.liberator.common.base.result.Response;
import lxs.tool.liberator.common.utils.IDCreator;
import lxs.tool.liberator.system.config.DynamicDataSource;
import lxs.tool.liberator.work.core.CodeMan;
import lxs.tool.liberator.work.mapper.ProjectMapper;
import lxs.tool.liberator.work.pojo.Project;
import lxs.tool.liberator.work.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Service("ProjectServiceImp")
public class ProjectServiceImp implements ProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private CodeMan codeMan;

    @Override
    public Response add(Project project) {
        project.setId(IDCreator.get("project"));
        projectMapper.insert(project);
        return Response.success();
    }

    @Override
    public Response update(Project project) {
        projectMapper.updateById(project);
        DynamicDataSource.removeDataSource(project.getId());
        return Response.success();
    }

    @Override
    public Response getById(String id) {
        return Response.send(projectMapper.selectById(id));
    }

    @Override
    public Response showTable() {
        return Response.send(projectMapper.showTable());
    }

    @Override
    public Response getMainProject() {
        return Response.send(projectMapper.getMainProject());
    }

    @Override
    public Response setMain(String id, Integer main) {
        Project mainProject = projectMapper.getMainProject();
        if (mainProject != null) projectMapper.setMain(mainProject.getId(), 0);
        projectMapper.setMain(id, main);
        return Response.success();
    }

    @Override
    public Response generate(HttpServletResponse response) throws Exception {
        File generate = codeMan.generate(projectMapper.getMainProject());
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new FileInputStream(generate);
        response.reset();
        response.setContentType("application/zip;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(generate.getName().getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
        int read = inputStream.read();
        while (read != -1) {
            outputStream.write(read);
            outputStream.flush();
            read = inputStream.read();
        }
        inputStream.close();
        return Response.success("下载成功");
    }
}
